﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SiteParser.Core.Logging;

namespace SiteParser.Core.ParserEntities
{
	public class ItemParser : ParserEntity
	{
		public bool PageBreak { get; set; }

		protected override void ProcessCurrentContext(ParsingContext context, IHtmlIterator htmlIterator) {
			Logger.Info("Processing current context for 'ItemParser'");

			//Null parent context means that new page started
			if (PageBreak) {
				context.ParentContext = null;
				Logger.Info("Page break added");
			}

			htmlIterator.MoveNext();
			var innerHtmlContext = Formatter.Format(htmlIterator.SelectedValue);

			Logger.Info(string.Format("Processing the next tag: TagName = {0}",
				string.IsNullOrEmpty(Expression.TagMatchingRule.Name) ? "*" : Expression.TagMatchingRule.Name));

			//If no child parser exists, then it meanse, that current selected value 
			//should be assigned to the current inner entity or to his property
			if (ChildEntities == null || ChildEntities.Count == 0) {
				Logger.Info(string.Format("Thereis no child parsers, trying to assign current selected value: {0}", innerHtmlContext));
				if (!string.IsNullOrEmpty(PropertyName)) {
					SetPropertyValue(context.InnerEntity, PropertyName, innerHtmlContext, true);
				}
				else {
					//If property name is not specified, that means we should assign selected value
					//directly to the Inner Entity
					context.InnerEntity = innerHtmlContext;
				}
			}
			else {

				Logger.Info(string.Format("Number of child parsers: {0}. Processing child items.", ChildEntities.Count));

				//If property is specified, then put this property as context object for child parsers,
				//otherwise put current context object as context object for child parsers
				object contextObject = string.IsNullOrEmpty(PropertyName) ? context.InnerEntity :
					InitializeProperty(context.InnerEntity, PropertyName);

				ParsingContext childContext = new ParsingContext()
				{
					InnerEntity = contextObject,
					InnerHtml = innerHtmlContext,
					CurrentUrl = context.CurrentUrl,
					ParentContext = context
				};

				ProcessChildEntities(childContext);
			}
		}
	}
}
